#!/usr/bin/env python3.1
#
# baseball.py
#
# This program reads korea pro baseball ranking data from naver.com
# in raw html data format and parse it and show in a table form
#
# programmed by ryuchihoon
# 2010.04.28
# 

import re
import os
import sys
import urllib.request
import urllib.error


def markuprepl(m):
	return ''
	
def delMarkup(s):
	return re.sub(r'<[^>]*?>', markuprepl, s)

if len(sys.argv) == 2:
	filepath = os.path.join(os.getcwd(), sys.argv[1])
	print("Reading data from '{0}'".format(filepath))
	f = open(filepath)
	s = f.read()
else:
	urladdr = r'http://kbodata.news.naver.com/m_rank/rank_team.asp'
	print("Reading data from '{0}'".format(urladdr))
	try:
		f = urllib.request.urlopen(urladdr)
		s = f.read().decode('euc-kr', 'ignore')
	except urllib.error.URLError:
		print("Can not connect to " + urladdr)
		quit(1)


c = re.compile(r'<table class="table_board2">(.*?)</table>', re.DOTALL)
t = c.search(s)
tablebody = t.group(1)

rowiter = re.compile(r'<tr>(.*?)</tr>', re.DOTALL).finditer(tablebody)

titles = []
rankdata = []

for i, rowmatch in enumerate(rowiter):
	row = rowmatch.group(1)
	
	coliter = re.compile(r'<td[^>]*?>(.*?)</td>', re.DOTALL).finditer(row)		
	d = [x.group(1) for x in coliter]
	
	if i == 0:
		# build titles
		titles = d
	else:
		# build data
		rankdata.append(list(map(delMarkup, d)))
		
		
print(titles)
for team in rankdata:
	print(team)
